package com.yami.shop.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.Agent;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.AgentService;
import com.yami.shop.service.ShopDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/agent/agent")
public class AgentController {

    @Autowired
    private AgentService agentService;
    @Autowired
    private ShopDetailService shopDetailService;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<Agent>> page(Agent agent, PageParam<Agent> page){
        IPage<Agent> agentList = agentService.page(page,new LambdaQueryWrapper<Agent>()
                .like(StrUtil.isNotBlank(agent.getAgentAddress()),Agent::getAgentAddress,agent.getAgentAddress())
                .orderByDesc(Agent::getAgentId));
        return ResponseEntity.ok(agentList);
    }


    /**
     * 获取信息
     */
    @GetMapping("/info/{id}")
//    @PreAuthorize("@pms.hasPermission('agent:agent:info')")
    public ResponseEntity<Agent> info(@PathVariable("id") Long id){
        Agent agent = agentService.getById(id);
        return ResponseEntity.ok(agent);
    }

    /**
     * 保存
     */
    @PostMapping
    public ResponseEntity<Void> save(@Valid @RequestBody Agent agent){
        Agent agent1 = agentService.selectRepeat(agent);
        if(agent1 == null){
            agentService.save(agent);
        }else{
            throw new YamiShopBindException("该用户已存在或该地级市已存在代理商");
        }

        return ResponseEntity.ok().build();
    }

    /**
     * 修改
     */
    @PutMapping
    public ResponseEntity<Void> update(@Valid @RequestBody Agent agent){
        Agent dbAgent = agentService.getById(agent.getAgentId());
        agentService.updateById(agent);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除
     */
    @DeleteMapping
    public ResponseEntity<Void> delete(@RequestBody Long[] ids){
        agentService.removeByIds(Arrays.asList(ids));
        return ResponseEntity.ok().build();
    }
}
